<template>
  <div id="main" ref="chartRef" class="chart" style="width: 100%; height: 350px;"></div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, watch} from "vue";
import { storeVuex } from '@/store/modules/user';
import { storeToRefs } from "pinia";
import * as echarts from "echarts";
import {order} from "@/api";
import {ElMessage} from "element-plus";

// storeToRefs设置为响应式状态
const isDarkMode = storeToRefs(storeVuex());

// let props = defineProps({
//   list: { type: Array, default: () => [] } // 为 props.list 提供默认值
// });


let myChart:any = null; // 存储 ECharts 实例


let listData = reactive([])
const initChart = () => {
  if (!listData || listData.length === 0) {
    console.warn("No data available for the chart.");
    return; // 如果没有数据，则不进行绘制
  }
  let e = listData
  var chartDom = document.getElementById('main');
  myChart = echarts.init(chartDom, isDarkMode.isDarkMode.value ? 'dark' : 'light');

  const option = {
    tooltip: {
      trigger: 'item',
      backgroundColor: isDarkMode.isDarkMode.value ? '#000000' : '#fff',
      textStyle: {
        color: isDarkMode.isDarkMode.value ? '#fff' : '#000',
      }
    },
    legend: {
      orient: 'vertical',
      left: '50',
      textStyle: {
        color: isDarkMode.isDarkMode.value ? '#fff' : '#000',
      }
    },
    grid: {
      left: '2%',
      right: '4%',
      bottom: '14%',
      top:'5%',
      containLabel: true
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: '90%',
        center: ['70%', '50%'],
        data: e,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
          label: {
            textStyle: {
              color: isDarkMode.isDarkMode.value ? '#fff' : '#000',
            }
          }
        }
      }
    ],
    backgroundColor: isDarkMode.isDarkMode.value ? '#1d1e1f' : '#fff',
  };

  myChart.setOption(option);
}

onMounted(() => {
  getSaleData();
});
let userStore = storeVuex();
const getSaleData = async ()=>{
  const res= await order.getOrderData({
    shop_id:userStore.userType_id
  })
  listData = res.data.data.data.echartsData
    initChart(listData);
}
// 监听深色模式变化
// watch(() => isDarkMode.isDarkMode.value, () => {
//   initChart(listData); // 重新初始化图表
// });

watch(
    [
      () => isDarkMode.isDarkMode.value,
      () => isDarkMode.isEcharts.value
    ],
    ([newDarkMode, newEchartsStatus]) => {
      // 如果深色模式变化
      if (newDarkMode !== undefined) {
        initChart(); // 重新初始化图表
      }
      // 如果导航栏隐藏状态变化
      if (newEchartsStatus !== undefined) {
        setTimeout(() => {
          updatewidth(); // 调整图表大小
        }, 1000);
      }
    }
);
const updatewidth = ()=>{
  myChart.resize();
}
</script>

<style scoped>

</style>
